<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>WebSocket Chat</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .container {
            min-height: 100vh;
            width: 88%;
        }

        .container>h1 {
            text-align: center;
        }

        .top {
            display: flex;
            justify-content: center;
            align-items: center;
        }

        #messages {
            display: inline-block;
            text-align: center;
            border: 3px solid black;
            padding: 10px;
            height: 300px;
            width: 66%;
            overflow-y: scroll;
            margin-bottom: 10px;
            border-top-left-radius: 50px;
            border-bottom-left-radius: 50px;
        }

        #users {
            margin-left: 10px;
            text-align: center;
            display: inline-block;
            width: 25%;
            height: 300px;
            border: 3px solid black;
            margin-bottom: 10px;
            padding: 10px;
            border-top-right-radius: 50px;
            border-bottom-right-radius: 50px;
            overflow-y: scroll;
        }

        #users::-webkit-scrollbar {
            display: none;
        }

        #msgInput {
            width: 70%;
            padding: 5px;
        }

        button {
            padding: 5px 10px;
        }

        #error {
            color: red;
            margin-top: 10px;
        }

        .user {
            cursor: pointer;
            color: blue;
        }

        #privateMessages {
            border: 3px solid black;
            padding: 10px;
            height: 300px;
            width: 66%;
            overflow-y: scroll;
            margin-bottom: 10px;
            display: none;
            border-top-left-radius: 50px;
            border-bottom-left-radius: 50px;
        }

        #toggleMessages {
            margin-top: 10px;
        }

        #messages p {
            text-align: center;
        }

        #privateMessages p {
            text-align: center;
        }
    </style>
</head>

<body>
<div class="container">
    <h1>海带聊天室</h1>
    <div class="top">
        <div id="messages"></div>
        <div id="privateMessages"></div>
        <div id="users">
            <span>在线用户</span>
            <ul id="userList"></ul>
        </div>
    </div>
    <button id="toggleMessages" onclick="toggleMessages()">切换到私聊</button>
    <input type="text" id="recipient" placeholder="接收者（留空发送给所有人）"
           style="width: 22%; padding: 5px; margin-bottom: 10px;">
    <input type="file" id="fileInput" style="width: 22%; padding: 5px; margin-bottom: 10px;">
    <input type="text" id="msgInput" placeholder="输入消息...">
    <button onclick="send()">发送</button>
    <!-- 在 body 标签内添加一个按钮 -->
    <button id="showHistory" onclick="showMessageHistory()">查看消息历史</button>
    <div id="historyMessages" style="display: none; border: 3px solid black; padding: 10px; height: 300px; width: 66%; overflow-y: scroll; margin-bottom: 10px;"></div>
    <div id="error"></div>
</div>
<script>
    // 获取用户名参数
    const urlParams = new URLSearchParams(window.location.search);
    let username = urlParams.get('user');
    // 使用 localStorage 存储用户名
    if (!username) {
        username = localStorage.getItem('chatUsername');
        if (!username) {
            username = `用户_${Date.now().toString(36)}`;
            localStorage.setItem('chatUsername', username);
        }
    }
    // 动态生成 WebSocket URL
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const ws = new WebSocket(`${protocol}//${window.location.host}/websocket?user=${username}`);

    // 接收消息
    ws.onmessage = (event) => {
        const message = JSON.parse(event.data);
        console.log("收到消息:", message);
        switch (message.type) {
            case 'JOIN':
                document.getElementById("messages").innerHTML += `<p><strong>管理员【海带】:</strong> ${message.user} 加入聊天室</p>`;
                break;
            case 'LEAVE':
                document.getElementById("messages").innerHTML += `<p><strong>管理员【海带】:</strong> ${message.user} 离开聊天室</p>`;
                break;
            case 'MESSAGE':
                if (message.user === 'all') {
                    document.getElementById("messages").innerHTML += `<p><strong class="user" onclick="startPrivateChat('${message.sender}')">${message.sender}:</strong> ${message.text} <span style="font-size: 0.8em;">(${message.timestamp})</span></p>`;
                } else {
                    document.getElementById("privateMessages").innerHTML += `<p><strong class="user" onclick="startPrivateChat('${message.sender}')">${message.sender}:</strong> ${message.text} <span style="font-size: 0.8em;">(${message.timestamp})</span></p>`;
                }
                break;
            case 'ERROR':
                document.getElementById("error").innerText = message.text;
                // 设置定时器在一秒后清除错误消息
                setTimeout(() => {
                    document.getElementById("error").innerText = '';
                }, 1000);
                break;
            case 'FILE':
                const messagesDiv = message.user === 'all' ? document.getElementById("messages") : document.getElementById("privateMessages");
                const p = document.createElement('p');
                const a = document.createElement('a');
                a.href = `data:${message.fileType};base64,${message.file}`;
                a.download = message.filename;
                a.textContent = message.filename;
                p.textContent = `${message.sender}: `;
                p.appendChild(a);
                p.innerHTML += ` <span style="font-size: 0.8em;">(${message.timestamp})</span>`;
                messagesDiv.appendChild(p);
                break;
            case 'USERS': // 添加对 USERS 消息类型的处理
                updateUsersList(message.users);
                break;
            case 'HISTORY':
                historyDiv.innerHTML = '';
                message.messages.forEach(msg => {
                    try {
                        const parsedMsg = JSON.parse(msg);
                        const p = document.createElement('p');
                        if (parsedMsg.type === 'FILE') {
                            const a = document.createElement('a');
                            a.href = `data:${parsedMsg.fileType};base64,${parsedMsg.file}`;
                            a.download = parsedMsg.filename;
                            a.textContent = parsedMsg.filename;
                            p.textContent = `${parsedMsg.sender}: `;
                            p.appendChild(a);
                        } else {
                            p.textContent = `${parsedMsg.sender}: ${parsedMsg.text} (${parsedMsg.timestamp})`;
                        }
                        historyDiv.appendChild(p);
                    } catch (error) {
                        console.error("Error parsing message in HISTORY:", error);
                        p.textContent = "无法解析的消息";
                        historyDiv.appendChild(p);
                    }
                });
                historyDiv.style.display = 'block';
                break;
            default:
                console.warn("未知消息类型:", message.type);
        }
    };


    // 更新在线用户列表
    function updateUsersList(users) {
        const userList = document.getElementById("userList");
        userList.innerHTML = '';
        users.forEach(user => {
            const li = document.createElement("li");
            li.textContent = user;
            userList.appendChild(li);
        });
    }

    // 文件上传处理函数
    function uploadFile(callback) {
        const fileInput = document.getElementById('fileInput');
        const file = fileInput.files[0];
        if (!file) {
            callback(null, null);
            return;
        }
        const reader = new FileReader();
        reader.onload = function(event) {
            const base64File = event.target.result.split(',')[1]; // 获取文件的 base64 编码
            callback(base64File, file.name, file.type);
        };
        reader.onerror = function(event) {
            console.error('文件读取错误:', event);
            callback(null, null);
        };
        reader.readAsDataURL(file);
    }

    // 发送消息
    function send() {
        const msgInput = document.getElementById("msgInput").value;
        const recipient = document.getElementById('recipient').value || 'all';

        uploadFile((base64File, filename, fileType) => {
            if (msgInput.trim() === '' && !base64File) {
                alert('请输入消息或选择文件');
                return;
            }

            const messages = [];
            if (msgInput.trim() !== '') {
                messages.push({
                    type: 'MESSAGE',
                    user: recipient,
                    text: msgInput,
                    timestamp: new Date().toISOString()
                });
            }

            if (base64File) {
                messages.push({
                    type: 'FILE',
                    user: recipient,
                    file: base64File,
                    filename: filename,
                    fileType: fileType,
                    timestamp: new Date().toISOString()
                });
            }

            messages.forEach(msg => {
                ws.send(JSON.stringify(msg));
            });

            document.getElementById("msgInput").value = ''; // 清空输入框
            document.getElementById("fileInput").value = ''; // 清空文件输入框
        });
    }

    // 连接成功后显示欢迎信息
    ws.onopen = () => {
        document.getElementById("messages").innerHTML += `<p><strong>管理员【海带】:</strong> 欢迎 ${username} 加入聊天室</p>`;
    };

    // 连接关闭后显示提示信息
    ws.onclose = () => {
        document.getElementById("messages").innerHTML += `<p><strong>管理员【海带】:</strong> ${username} 已离开聊天室</p>`;
    };

    // 处理错误
    ws.onerror = (error) => {
        console.error('WebSocket 错误:', error);
        document.getElementById("error").innerText = '发生错误，请刷新页面重试';
    };

    // 私聊功能
    function startPrivateChat(user) {
        document.getElementById('recipient').value = user;
    }

    // 切换消息显示
    function toggleMessages() {
        const messages = document.getElementById("messages");
        const privateMessages = document.getElementById("privateMessages");
        const toggleButton = document.getElementById("toggleMessages");

        if (messages.style.display === 'none') {
            messages.style.display = 'block';
            privateMessages.style.display = 'none';
            toggleButton.innerText = '切换到私聊';
        } else {
            messages.style.display = 'none';
            privateMessages.style.display = 'block';
            toggleButton.innerText = '切换到公共消息';
        }
    }

    // 在 script 标签内添加以下函数
    function showMessageHistory() {
        const historyDiv = document.getElementById('historyMessages');
        if (historyDiv.style.display === 'block') {
            historyDiv.style.display = 'none';
        } else {
            // 修改请求路径为 /websocket 并发送 GET_HISTORY 类型的消息
            const message = JSON.stringify({ type: 'GET_HISTORY' });
            ws.send(message);
            // 重置 ws.onmessage 以避免覆盖其他消息处理逻辑
            const originalOnMessage = ws.onmessage;
            ws.onmessage = (event) => {
                const message = JSON.parse(event.data);
                if (message.type === 'HISTORY') {
                    historyDiv.innerHTML = '';
                    message.messages.forEach(msg => {
                        try {
                            const parsedMsg = JSON.parse(msg);
                            const p = document.createElement('p');
                            if (parsedMsg.type === 'FILE') {
                                const a = document.createElement('a');
                                a.href = `data:${parsedMsg.fileType};base64,${parsedMsg.file}`;
                                a.download = parsedMsg.filename;
                                a.textContent = parsedMsg.filename;
                                p.textContent = `${parsedMsg.sender}: `;
                                p.appendChild(a);
                            } else {
                                p.textContent = `${parsedMsg.sender}: ${parsedMsg.text} (${parsedMsg.timestamp})`;
                            }
                            historyDiv.appendChild(p);
                        } catch (error) {
                            console.error("Error parsing message in HISTORY:", error);
                            p.textContent = "无法解析的消息";
                            historyDiv.appendChild(p);
                        }
                    });
                    historyDiv.style.display = 'block';
                } else {
                    // 调用原始的 onmessage 处理逻辑
                    originalOnMessage(event);
                }
            };
        }
    }
    // 确保 DOM 完全加载后再执行脚本
    document.addEventListener('DOMContentLoaded', function() {
        // 修改发送按钮的点击事件，添加文件上传功能
        document.getElementById('send').addEventListener('click', send);
    });
</script>
</body>

</html>
